package com.skwyb.form.service.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skwyb.form.bean.dto.SysAdmin;
import com.skwyb.form.constants.ResultCode;
import com.skwyb.form.mapper.SysAdminMapper;
import com.skwyb.form.utils.AssertUtils;
import com.skwyb.form.utils.CryptUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;

/**
 * @author Administrator
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AdminService extends ServiceImpl<SysAdminMapper, SysAdmin> {

    private final SysAdminMapper adminMapper;

    @Override
    public boolean saveOrUpdate(SysAdmin entity) {
        if (StringUtils.isNotBlank(entity.getId())) {
            SysAdmin sysAdmin = super.getById(entity.getId());
            AssertUtils.isFalse(null == sysAdmin, ResultCode.NOT_FOUND);
            if (!entity.getPassword().equals(sysAdmin.getPassword())) {
                sysAdmin.setPassword(CryptUtil.md5AesHex(entity.getPassword()));
            }
        }
        AssertUtils.isTrue(isRepeatAccount(entity.getAccount(), entity.getId()), ResultCode.REPEAT_ACCOUNT);
        return super.saveOrUpdate(entity);
    }

    private boolean isRepeatAccount(String account, String id) {
        if (StringUtils.isBlank(id)) {
            //是否新增
            return null == selectByAccount(account);
        } else {
            Map<String, Object> map = getMap(Wrappers.lambdaQuery(new SysAdmin().setAccount(account)).ne(SysAdmin::getId, id));
            return null != map;
        }
    }

    public SysAdmin selectByAccount(String account) {
        return getOne(Wrappers.lambdaQuery(new SysAdmin().setAccount(account)));
    }

    @Override
    public boolean removeById(Serializable id) {
        SysAdmin sysAdmin = getById(id);
        AssertUtils.isFalse(null == sysAdmin, ResultCode.NOT_FOUND);
        AssertUtils.isFalse(sysAdmin.getIsSystem(), ResultCode.IS_SYSTEM);
        return super.removeById(id);
    }
}
